package com.asiainfo.iov.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.iov.configs.ConstantsME;
import com.asiainfo.iov.configs.IntentCode;
import com.asiainfo.iov.configs.InterfaceConfig;
import com.asiainfo.iov.networkModel.HttpUtil;
import com.framework.customviews.OverScrollView;
import com.framework.security.RSAmethodInAssets;
import com.framework.utils.KeyBoardUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.RegularUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.ToastUtil;
import com.framework.utils.Y;
import com.framework2.popupwindow.BindingPhonePopupwindow;
import com.framework2.util.ConstantRequestUtil;
import com.framework2.util.CustomLoadingDialogUtils;
import com.framework2.util.GlideUtil;
import com.framework2.util.PicToastUtil;
import com.library.percent.PercentRelativeLayout;
import com.yaxin.yyt.R;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 登录注册
 *
 * @author YobertJomi
 * className LoginActivity
 * created at  2017/3/13  16:24
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.etLoginPhone)
    EditText etLoginPhone;
    @BindView(R.id.etLoginPassword)
    EditText etLoginPassword;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.loginLayout)
    LinearLayout loginLayout;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.overScrollView)
    OverScrollView overScrollView;
    @BindView(R.id.wchatLogin)
    LinearLayout wchatLogin;
    @BindView(R.id.qqLogin)
    LinearLayout qqLogin;
    @BindView(R.id.ivQuickLogin)
    ImageView ivQuickLogin;
    @BindView(R.id.tvQuickLogin)
    TextView tvQuickLogin;
    @BindView(R.id.tvOtherLogin)
    TextView tvOtherLogin;
    @BindView(R.id.layoutQuickLogin)
    PercentRelativeLayout layoutQuickLogin;
    @BindView(R.id.tvQuickLoginProtocol)
    TextView tvQuickLoginProtocol;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_login_by_captcha)
    TextView tvLoginByCaptcha;
    @BindView(R.id.groupOtherLogin)
    RelativeLayout groupOtherLogin;
    @BindView(R.id.groupInnerOtherLogin)
    PercentRelativeLayout groupInnerOtherLogin;
    @BindView(R.id.tvNormalLoginProtocol)
    TextView tvNormalLoginProtocol;

    private String phoneTemp;
    private String pwdTemp;
    private String captchaTemp;
    private MyCountDownTimer myCountDownTimer;
    private String verifyKey;//验证码key

    private Animation enterAnimation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        ScreenUtils.getInstance().setSystemUiColorDark(this, false);//设置状态栏字体颜色浅

        initGif();
        initData();
        initEvent();
        initAnimation();
    }

    private void initAnimation() {
        layoutQuickLogin.setVisibility(View.VISIBLE);
        enterAnimation = AnimationUtils.loadAnimation(this, R.anim.set_show_login);
        layoutQuickLogin.setAnimation(enterAnimation);
    }

    private void initGif() {
        layoutQuickLogin.setVisibility(View.VISIBLE);
        groupOtherLogin.setVisibility(View.GONE);
        GlideUtil.getInstance().showLocalImage(LoginActivity.this, R.mipmap.gif_quick_login, ivQuickLogin);
    }

    private void initData() {
        String phone = RSAmethodInAssets.rsaDecrypt(this,
                PreferencesHelper.getInstance().getStringData(ConstantsME.PHONE));
        if (!TextUtils.isEmpty(phone)) {
            etLoginPhone.setText(phone);
            etLoginPhone.setSelection(phone.length());
            etLoginPhone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, false);
        }
        if (!TextUtils.isEmpty(phone)) {
            etLoginPhone.setText(phone);
            etLoginPhone.setSelection(phone.length());
            etLoginPassword.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this,
                    etLoginPhone, true);
        }
        String quickLoginProtocol = getResources().getString(R.string.iov_login_quicklogin_protocol);
        SpannableString spannableString = new SpannableString(quickLoginProtocol);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.iov_protocol)), quickLoginProtocol.indexOf("《"),
                quickLoginProtocol.indexOf("》") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvQuickLoginProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        spannableString.setSpan(new OnClickSpan(), quickLoginProtocol.indexOf("《"),
                quickLoginProtocol.indexOf("》") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvQuickLoginProtocol.setText(spannableString);

        String loginProtocol = getResources().getString(R.string.iov_login_protocol);
        SpannableString loginProtocolSS = new SpannableString(loginProtocol);
        loginProtocolSS.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.iov_protocol)), loginProtocol.indexOf("《"),
                loginProtocol.indexOf("》") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvNormalLoginProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        loginProtocolSS.setSpan(new OnClickSpan(), loginProtocol.indexOf("《"),
                loginProtocol.indexOf("》") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvNormalLoginProtocol.setText(loginProtocolSS);
    }

    private void initEvent() {
        overScrollView
                .setOverScrollTinyListener(new OverScrollView.OverScrollTinyListener() {
                    @Override
                    public void scrollLoosen() {

                    }

                    @Override
                    public void scrollDistance(int tinyDistance,
                                               int totalDistance) {
                        KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this,
                                etLoginPhone, true);
                    }
                });
    }

    private boolean isLegal(EditText et_phone, EditText et_password, EditText et_captcha) {
        if (null == et_phone || null == et_password)
            return false;
        if (TextUtils.isEmpty(et_phone.getText())) {
            PicToastUtil.getInstance().showToast(LoginActivity.this, "请输入你的手机号码!");
            et_phone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        } else if (!RegularUtil.getInstance().isMobileNO(et_phone.getText().toString())) {
            PicToastUtil.getInstance().showToast(LoginActivity.this, "请输入正确的手机号码!");
            et_phone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        } else if (TextUtils.isEmpty(et_password.getText())) {
            PicToastUtil.getInstance().showToast(LoginActivity.this, "请输入密码!");
            et_password.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        } else if (null != et_captcha && !TextUtils.isEmpty(et_captcha.getText())) {
            PicToastUtil.getInstance().showToast(LoginActivity.this, "请输入验证码!");
            et_captcha.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, et_phone, false);
            return false;
        }
        return true;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(this, etLoginPhone, true);
                initGif();
                break;
            case R.id.tvQuickLogin:
                PicToastUtil.getInstance().showToast(LoginActivity.this, "一键登录");
                break;
            case R.id.tvOtherLogin:
                ivQuickLogin.setImageResource(R.mipmap.gif_quick_login);
                groupOtherLogin.setVisibility(View.VISIBLE);
                layoutQuickLogin.setVisibility(View.GONE);
                break;
            case R.id.tv_login_by_captcha:
                startActivity(LoginCaptchaActivity.class);
                break;
            case R.id.tv_forget_pwd:
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, true);
                Bundle forgetBundle = new Bundle();
                if (!TextUtils.isEmpty(etLoginPhone.getText()) && RegularUtil.getInstance().isMobileNO(etLoginPhone
                        .getText().toString()))
                    forgetBundle.putString(ConstantsME.PHONE, etLoginPhone.getText().toString());
                startActivityForResult(ForgetPasswordActivity.class, forgetBundle, IntentCode.login);
                break;
            case R.id.tv_login:
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, true);
                if (isLegal(etLoginPhone, etLoginPassword, null)) {
                    CustomLoadingDialogUtils.showProcessDialog(LoginActivity.this, "正在登录");
                    requestLogin();
                }
                break;
            case R.id.tv_register:
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(LoginActivity.this, etLoginPhone, true);
                Bundle bundle = new Bundle();
                if (!TextUtils.isEmpty(etLoginPhone.getText()) && RegularUtil.getInstance().isMobileNO(etLoginPhone
                        .getText().toString()))
                    bundle.putString(ConstantsME.PHONE, etLoginPhone.getText().toString());
                startActivityForResult(RegisterActivity.class, bundle, IntentCode.login);
                break;
            default:
                break;
        }
    }

    /**
     * login
     */
    private void requestLogin() {
        HttpUtil.getInstance().requestLogin(InterfaceConfig.login, etLoginPhone.getText().toString(), etLoginPassword
                .getText().toString(), new HttpUtil.OnRequestResult<String>() {
            @Override
            public void onSuccess(String... msg) {
//                CustomProgressDialogUtils.dismissProcessDialog();
                PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE, RSAmethodInAssets.rsaEncrypt(LoginActivity
                                .this,
                        etLoginPhone.getText().toString()));
                PreferencesHelper.getInstance().putInfo(ConstantsME.token, msg != null ? msg[0] : "");
                PreferencesHelper.getInstance().putInfo(ConstantsME.nick, msg != null ? msg[1] : "");
                PreferencesHelper.getInstance().putInfo(ConstantsME.imgUrl, msg != null ? msg[2] : "");
                PreferencesHelper.getInstance().putInfo(ConstantsME.LOGINED, true);

                CustomLoadingDialogUtils.showProcessDialog(LoginActivity.this, "检查店铺");
                ConstantRequestUtil.getInstance().requestJustShopIds(LoginActivity.this);
            }

            @Override
            public void onFail(int code, String msg) {
                CustomLoadingDialogUtils.dismissProcessDialog();
                ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "登录失败" : msg);
            }
        });
    }

    private void showBindingPop(final int type, String phone, final String openId, final String pwd, final String
            captcha) {
        CustomLoadingDialogUtils.dismissProcessDialog();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED | WindowManager
                .LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        final BindingPhonePopupwindow pop = new BindingPhonePopupwindow(LoginActivity.this);
//        pop.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEND) {
//                    if (!TextUtils.isEmpty(v.getText())) {
//                        Utils.isCloseSoftInputMethod(LoginActivity.this, null, true);
//                        CustomProgressDialogUtils.showProcessDialog(LoginActivity.this, "正在绑定手机号");
//                        requestThirdLoginBindPhone(type, v.getText().toString(), openId, imgUrl, nick);
//                        pop.dismiss();
//                    } else {
//                        pop.getEditText().requestFocus();
//                        PicToastUtil.getInstance().showToast(LoginActivity.this, "请输入电话号码");
//                    }
//                    return true;
//                }
//                return false;
//            }
//        });
        long last = PreferencesHelper.getInstance().getLongData(ConstantsME.captcha_last_clicked);
        long currentTimeMillis = System.currentTimeMillis();
        long difference = currentTimeMillis - last;
        int diff = (int) ((60 * 1000 - difference) / 1000);
        Y.y("last:" + last);
        Y.y("currentTimeMillis:" + currentTimeMillis);
        Y.y("difference:" + difference);
        if (difference < 60 * 1000 && diff >= 1) {
            new MyCountDownTimer(pop.getCaptcaTextView(), diff * 1000, 1000).start();
        }
        pop.setContent(phone).setPassword(pwd).setCaptcha(captcha).setOnGetCaptchaListener(new BindingPhonePopupwindow.OnGetCaptchaListener() {
            @Override
            public void onGetCaptchaListener(String phoneNum) {
                myCountDownTimer = new MyCountDownTimer(pop.getCaptcaTextView(), 60000, 1000);
                myCountDownTimer.start();
                PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, System.currentTimeMillis());
                CustomLoadingDialogUtils.showProcessDialog(LoginActivity.this, "获取验证码");
                requestCaptcha(pop.getCaptcaTextView(), phoneNum);
            }
        });
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager
                        .LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            }
        });
        pop.setOnSureClickListener(new BindingPhonePopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String phone, String pwd, String captcha) {
                phoneTemp = phone;
                pwdTemp = pwd;
                captchaTemp = captcha;
                if (TextUtils.isEmpty(verifyKey)) {
                    ToastUtil.getInstance().showToast("请先获取验证码");
                }
            }
        }).showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 请求获取验证码
     */
    private void requestCaptcha(final TextView tv_captcha, String phone) {
        HttpUtil.getInstance().requestMobileVerify(InterfaceConfig.captcha, 4, phone,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast("获取验证码成功");
                        if (null != s && !TextUtils.isEmpty(s[0])) {
                            verifyKey = s[0];
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "获取验证码失败" : msg);
                        PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, 0L);
                        if (null != myCountDownTimer)
                            myCountDownTimer.cancel();
                        tv_captcha.setText("重新获取");
                        tv_captcha.setTextColor(getResources().getColor(R.color._blue));
                        tv_captcha.setClickable(true);
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == Activity.RESULT_OK && requestCode == IntentCode.login) {
            String phone = data.getStringExtra(ConstantsME.PHONE);
            if (!TextUtils.isEmpty(phone)) {
                etLoginPhone.setText(phone);
                etLoginPassword.requestFocus();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class MyCountDownTimer extends CountDownTimer {
        private TextView tv_captcha;

        public MyCountDownTimer(TextView tv_captcha, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
            this.tv_captcha = tv_captcha;
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            tv_captcha.setText("重新获取");
            tv_captcha.setTextColor(getResources().getColor(R.color._blue));
            tv_captcha.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            try {
                tv_captcha.setClickable(false);
                tv_captcha.setTextColor(getResources().getColor(
                        R.color.trans));
                tv_captcha.setText(millisUntilFinished / 1000 + "秒");
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private class OnClickSpan extends ClickableSpan {

        @Override
        public void onClick(View widget) {
            PicToastUtil.getInstance().showToast(LoginActivity.this, "跳转到H5");
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            //去除超链接的下划线
            ds.setUnderlineText(false);
            //重新设置文字背景为透明色。
            tvQuickLoginProtocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
        }
    }
}
